package cn.kooki.app.duobao.ui.Activity.Goods;

import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseActivity;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.Index.GoodsItem;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.detail.GoodDetailResponse;
import cn.kooki.app.duobao.data.Bean.detail.JionIninfo;
import cn.kooki.app.duobao.data.Bean.detail.JionResponse;
import cn.kooki.app.duobao.data.bus.ChangePageEvent;
import cn.kooki.app.duobao.data.bus.LoginChangeEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.presenter.HeaderController;
import cn.kooki.app.duobao.ui.Activity.Comm.RootAcitivity;
import cn.kooki.app.duobao.ui.Adapter.DetaillistAdpater;
import cn.kooki.app.duobao.ui.view.CustomRefreshHeader;
import cn.kooki.app.duobao.ui.view.LoadMoreContainer;
import cn.kooki.app.duobao.ui.view.LoadMoreHandler;
import cn.kooki.app.duobao.ui.view.LoadMoreListViewContainer;
import cn.kooki.app.duobao.ui.view.LoadingProgressView;
import cn.kooki.app.duobao.ui.widget.AddShopCartPopWin;
import cn.kooki.app.duobao.ui.widget.banner.SliderBanner;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.StringUtils;
import cn.kooki.app.duobao.util.manager.AppManager;
import cn.kooki.app.duobao.util.manager.CartObserver;
import cn.kooki.app.duobao.util.manager.ShopCartManager;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;


/**
 * Created by xionghao on 15/12/11.
 */
public class GoodsDetailAcitvity extends BaseActivity implements View.OnClickListener, CartObserver, AddShopCartPopWin.AddBtnClickListener {


    @Bind(R.id.top_back)
    ImageButton topBack;
    @Bind(R.id.top_text_center)
    TextView topTextCenter;
    @Bind(R.id.top_cart)
    ImageButton topCart;
    @Bind(R.id.action_edit)
    TextView actionEdit;
    @Bind(R.id.toolbar)
    RelativeLayout toolbar;
    @Bind(R.id.iv_loading)
    LoadingProgressView ivLoading;
    @Bind(R.id.tv_loading)
    TextView tvLoading;
    @Bind(R.id.load_error_icon)
    ImageView loadErrorIcon;
    @Bind(R.id.layout_loading)
    RelativeLayout layoutLoading;
    @Bind(R.id.tv_empty)
    TextView tvEmpty;
    @Bind(R.id.lv_joinList)
    ListView lvJoinList;
    @Bind(R.id.detailActivity_customSwipeRefreshLayout)
    PtrFrameLayout detailActivityCustomSwipeRefreshLayout;
    @Bind(R.id.tv_buyDesc)
    TextView tvBuyDesc;
    @Bind(R.id.layout_buyDisable)
    LinearLayout layoutBuyDisable;
    @Bind(R.id.bt_joinNow)
    Button btJoinNow;
    @Bind(R.id.bt_addGood2Cart)
    Button btAddGood2Cart;
    @Bind(R.id.cart_icon)
    ImageView cartIcon;
    @Bind(R.id.cart_num)
    TextView cartNum;
    @Bind(R.id.cart_icon_wrapper)
    RelativeLayout cartIconWrapper;
    @Bind(R.id.layout_buyNow)
    LinearLayout layoutBuyNow;
    @Bind(R.id.tv_currentNow)
    TextView tvCurrentNow;
    @Bind(R.id.bt_goCurrentPeriod)
    Button btGoCurrentPeriod;
    @Bind(R.id.layout_goCurrent)
    RelativeLayout layoutGoCurrent;
    @Bind(R.id.layout_bottomBar)
    RelativeLayout layoutBottomBar;
    @Bind(R.id.layout_detail)
    FrameLayout layoutDetail;
    @Bind(R.id.animation_wrapper)
    RelativeLayout animationWrapper;
    @Bind(R.id.load_more_list_view_container)
    LoadMoreListViewContainer loadMoreListViewContainer;

    private SliderBanner slider;

    private ArrayList<JionIninfo> datas = new ArrayList<>();
    private DetaillistAdpater adpater;
    private String id;
    private String qishu;
    private GoodsItem data;
    private View header;
    private HeaderController headerController;
    private int page = 1;
    private AddShopCartPopWin shopCartPopWin;
    private String new_id;
    private String new_qishu;



    @Override
    protected void setToolbar() {
        topBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        topBack.setVisibility(View.VISIBLE);
        topTextCenter.setText(R.string.title_activity_detail);
        topTextCenter.setVisibility(View.VISIBLE);
        topCart.setImageResource(R.drawable.ic_home_black);
        topCart.setVisibility(View.VISIBLE);
        topCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new ChangePageEvent());
                AppManager.getAppManager().getTopWith(RootAcitivity.class);
            }
        });
    }


    @Override
    protected void setLayoutContentView() {
        setContentView(R.layout.activity_detail);
        header = View.inflate(this, R.layout.layout_detail_listheader, null);
        ButterKnife.bind(this);
        headerController = new HeaderController(header, this);

    }

    public void onEventMainThread(LoginChangeEvent event) {
        getdata(false);
    }

    private int repeatcount = 0;

    @Override
    protected void afterView() {
        headerController.setCompleteListener(new HeaderController.CountCompeleteListener() {
            @Override
            public void onCompelte() {

                if (repeatcount < 10) {
                    getdata(false);
                    repeatcount++;
                }
            }
        });
        ShopCartManager.getInstance().changeObservable.registerObserver(this);
        id = getIntent().getStringExtra("id");
        qishu = getIntent().getStringExtra("qishu");
        lvJoinList.addHeaderView(header);
        CustomRefreshHeader refreshHeader = new CustomRefreshHeader(this);
        detailActivityCustomSwipeRefreshLayout.addPtrUIHandler(refreshHeader);
        detailActivityCustomSwipeRefreshLayout.setHeaderView(refreshHeader);
        detailActivityCustomSwipeRefreshLayout.disableWhenHorizontalMove(true);
        layoutBuyNow.setVisibility(View.VISIBLE);
        adpater = new DetaillistAdpater(this, datas);
        lvJoinList.setAdapter(adpater);
        layoutDetail.setVisibility(View.GONE);
        layoutLoading.setVisibility(View.VISIBLE);
        ivLoading.startAniation();
        detailActivityCustomSwipeRefreshLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                // here check list view, not content.
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvJoinList, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                repeatcount = 0;
                getdata(false);
            }
        });
        loadMoreListViewContainer.useDefaultFooter();
        loadMoreListViewContainer.setShowLoadingForFirstPage(true);
        loadMoreListViewContainer.setLoadMoreHandler(new LoadMoreHandler() {
            @Override
            public void onLoadMore(LoadMoreContainer loadMoreContainer) {
                getdata(true);
            }
        });
        btJoinNow.setOnClickListener(this);
        btAddGood2Cart.setOnClickListener(this);
        cartIconWrapper.setOnClickListener(this);
        getdata(false);
    }

    private void getdata(boolean b) {
        HashMap<String, String> params = new HashMap<>();
        boolean islogin = SharePreferencesUtils.getBoolean(this, SharePreferencesUtils.ISLOGIN);
        UserInfo userInfo = SharePreferencesUtils.getUserinfo(this);
        if (islogin) {
            params.put("uname", userInfo.getUid());
        }
        if (!b) {
            page = 0;
            MainFactory.getApiInstance().getdetail(id, qishu, params, new Callback<GoodDetailResponse>() {
                @Override
                public void success(GoodDetailResponse goodDetailResponse, Response response) {
                    if (goodDetailResponse.data != null) {
                        data = goodDetailResponse.data;
                        refreshView();
                        hideloading();
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    hideloading();
                }
            });

        } else {
            page++;
            MainFactory.getApiInstance().listshopRecord(id, qishu, page, new Callback<JionResponse>() {
                @Override
                public void success(JionResponse baseResponse, Response response) {
                    if (baseResponse.getData() != null) {
                        datas.addAll(baseResponse.getData());
                        loadMoreListViewContainer.loadMoreFinish(baseResponse.getData().size() == 0, baseResponse.getData().size() == Constants.DEFAULT_COUNT);
                        adpater.notifyDataSetChanged();
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    int errorCode = 0;
                    String errorMessage = "加载失败，点击加载更多";
                    loadMoreListViewContainer.loadMoreError(errorCode, errorMessage);
                }
            });
        }
    }

    private void hideloading() {
        layoutDetail.setVisibility(View.VISIBLE);
        ivLoading.stopAniation();
        layoutLoading.setVisibility(View.GONE);
        detailActivityCustomSwipeRefreshLayout.refreshComplete();
    }

    private void refreshView() {
        if (headerController != null) {
            headerController.setItem(data);
            headerController.refeshView();
        }
        refreshCarts();
        if (StringUtils.nullSafeParseInt(data.getStatus()) == 0) {
            layoutBuyNow.setVisibility(View.VISIBLE);
            layoutGoCurrent.setVisibility(View.GONE);
        } else {
            layoutGoCurrent.setVisibility(View.VISIBLE);
            layoutBuyNow.setVisibility(View.GONE);
            tvCurrentNow.setText("新一期正在火热进行中...");
            btGoCurrentPeriod.setOnClickListener(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        headerController.unbindView();
        if (shopCartPopWin != null) {
            shopCartPopWin = null;
        }
        ShopCartManager.getInstance().changeObservable.unregisterObserver(this);
    }

    @Override
    public void onClick(View v) {
        if (v == btJoinNow) {
            showAddPopwin(true);
        }
        if (v == btAddGood2Cart) {
            showAddPopwin(false);
        }
        if (v == btGoCurrentPeriod) {
            HashMap<String, String> keys = new HashMap<>();
            keys.put("id", data.getNew_id());
            keys.put("qishu", data.getNew_qishu());
            intent(GoodsDetailAcitvity.class, keys);
        }
        if (v == cartIconWrapper) {
            ChangePageEvent pageEvent = new ChangePageEvent();
            pageEvent.item = 3;
            EventBus.getDefault().post(pageEvent);
            AppManager.getAppManager().getTopWith(RootAcitivity.class);

        }
    }

    private void showAddPopwin(boolean isgoto) {
        if (shopCartPopWin == null) {
            shopCartPopWin = new AddShopCartPopWin(this);
            shopCartPopWin.setAddBtnClickListener(this);
        }
        shopCartPopWin.setIsduobao(isgoto);
        shopCartPopWin.setdata(data);
        shopCartPopWin.showInView(animationWrapper);
    }

    @Override
    public void onChanged(int count) {

    }

    @Override
    public void onCheckedChange(int count, boolean isCancelEditing) {

    }

    @Override
    public void onCartsChange() {
        refreshCarts();
    }

    private void refreshCarts() {
        int cartsSize = ShopCartManager.getInstance().getCartsSize();

        cartNum.setText(cartsSize + "");
        if (cartsSize == 0) {
            cartNum.setVisibility(View.GONE);
        } else {
            cartNum.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(int index) {
        if (index == 0) {

            ShopCartManager.getInstance().addShopCart(shopCartPopWin.getData());
            ChangePageEvent pageEvent = new ChangePageEvent();
            pageEvent.item = 3;
            EventBus.getDefault().post(pageEvent);
            AppManager.getAppManager().getTopWith(RootAcitivity.class);
        } else if (index == 1) {
            ShopCartManager.getInstance().addShopCart(shopCartPopWin.getData());
            showToastMessage("添加成功");
        }
    }
}
